#ifndef TCPCLIENT_H
#define TCPCLIENT_H

#include <QObject>
#include <QTcpSocket>
#include "TcpMessage.h"
#include <QQueue>

class TcpClient : public QObject
{
    Q_OBJECT
public:
    explicit TcpClient(QObject *parent = nullptr);

public:
    void connectToServer(QHostAddress ip, int port);
    void disconnectFromServer();
    QAbstractSocket::SocketState state();
    uint32_t sendMessage(MessageType type, QByteArray data);


signals:
    void connected();
    void recvLoginResponse();
    void recvHeartbeatResponse(uint32_t id);
    void recvRegResponse(GetRegResponseMessage regMessage);
    void recvRTKResponse();
    void recvRTKData(RTKDataMessage rtkMessage);
    void recvTrackDataV2(TrackDataV2Message trackData);
    void recvTrackDataV3(TrackDataV3Message trackData);

private slots:
    void onConnected();
    void onReadyRead();

private:
    QList<QByteArray> unpack(QByteArray &packet);

private:
    QTcpSocket *m_tcpSocket = nullptr;

    const static int headerLen = 2*sizeof(int32_t);
    const static int crc16Len = sizeof(uint16_t);
    const static int minMessageLen = headerLen + crc16Len; // nameLen + typeName + checkSum
    const static int maxMessageLen = 128*1024*1024; // same as codec_stream.h kDefaultTotalBytesLimit
    const static uint32_t headerMagic = 0x55AA55AA;
};

#endif // TCPCLIENT_H
